# encoding: utf-8
"""
@author: youfeng
@file: __lock.py
@time: 2018/8/12 下午10:42
"""

import time


# import redis
#
# # 调度缓存
# SCHEDULE_CACHE_CONF = {
#     "host": '192.168.0.90',
#     "port": 6379,
#     "password": 'haizhi@)',
#     "db": 3,
#     "max_connections": 200
# }
#
# redis_client = redis.StrictRedis(SCHEDULE_CACHE_CONF['host'],
#                                  SCHEDULE_CACHE_CONF['port'],
#                                  SCHEDULE_CACHE_CONF['password'],
#                                  SCHEDULE_CACHE_CONF['db'],
#                                  SCHEDULE_CACHE_CONF['max_connections'])


class RedisLock(object):
    LOCK_PRE = "redis:lock:"

    def __init__(self, __redis_client, log=None):
        self.log = log
        self.redis_client = __redis_client

    def __get_lock_key(self, key):
        return "{}{}".format(self.LOCK_PRE, key)

    def lock(self, key, timeout=5):
        __lock = 0
        lock_key = self.__get_lock_key(key)
        while __lock != 1:
            timestamp = time.time() + timeout + 1
            __lock = self.redis_client.setnx(lock_key, timestamp)
            if __lock == 1:
                break

            if time.time() > self.redis_client.get(lock_key) and time.time() > self.redis_client.getset(
                    lock_key,
                    timestamp):
                break
            time.sleep(0.1)
        self.log.info("加锁成功.")

    def release(self, key):
        lock_key = self.__get_lock_key(key)
        if time.time() < self.redis_client.get(lock_key):
            self.redis_client.delete(lock_key)
            self.log.info("解锁成功.")

# def deco(self):
#     def _deco(func):
#         def __deco(*args, **kwargs):
#             cls.get_lock(cls)
#             try:
#                 return func(*args, **kwargs)
#             finally:
#                 cls.release(cls)
#
#         return __deco
#
#     return _deco
#
#
# @deco(RedisLock("112233", redis_client))
# def myfunc():
#     print "myfunc() called."
#     time.sleep(20)

#
# if __name__ == "__main__":
#     myfunc()
